const { Controller } = require("egg");

class Useraddress extends Controller {
  // 创建收货地址
  async createAddress() {
    const { ctx } = this;
    const { phone, address, isDefault, name, detail, gender, label } =
      ctx.request.body;
    ctx.validate({
      phone: { type: "phone", fieldName: "手机号" },
      gender: { type: "nullValue", fieldName: "性别" },
      address: { type: "nullValue", fieldName: "地址" },
      name: { type: "nullValue", fieldName: "姓名" },
      detail: { type: "nullValue", fieldName: "地址详情" },
    });
    console.log("_id：", ctx.auth._id);
    const res = await ctx.model.Useraddress.create({
      userId: ctx.auth._id,
      phone,
      address,
      name,
      detail,
      isDefault,
      gender,
      label,
    });
    ctx.send({ msg: "成功", data: res.toObject() });
  }
  //   设置默认地址
  async setDefaultAddress() {
    const { ctx } = this;
    const { _id } = ctx.request.body;
    ctx.validate({ _id: { type: "nullValue", fieldName: "_id" } });
    await ctx.model.Useraddress.updateMany({}, { isDefault: false });
    await ctx.model.Useraddress.updateOne({ _id }, { isDefault: true });

    ctx.send({ msg: "成功" });
  }
  //   删除地址
  async deltAddress() {
    const { ctx } = this;
    const { _id } = ctx.params;
    ctx.validate({ _id: { type: "nullValue", fieldName: "_id" } },ctx.params);
    await ctx.model.Useraddress.deleteOne({ _id });

    ctx.send({ msg: "成功" });
  }
  //   获取所有地址
  async getAllAddress() {
    const { ctx } = this;
    const res = await ctx.model.Useraddress.find({ userId: ctx.auth._id });

    ctx.send({ msg: "成功", data: res });
  }
}
module.exports = Useraddress;
